import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/todo_item.dart';

// 待办事项列表Provider（使用Riverpod管理状态）
class TodosNotifier extends StateNotifier<List<TodoItem>> {
  TodosNotifier()
    : super([
        TodoItem(id: '1', title: '学习Flutter', isCompleted: false, createdAt: DateTime.now()),
        TodoItem(id: '2', title: '学习Riverpod', isCompleted: false, createdAt: DateTime.now()),
        TodoItem(id: '3', title: '学习Dio', isCompleted: true, createdAt: DateTime.now()),
      ]);

  // 添加待办事项
  void addTodo(String title) {
    final newTodo = TodoItem(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: title,
      isCompleted: false,
      createdAt: DateTime.now(),
    );
    state = [...state, newTodo];
  }

  // 切换完成状态
  void toggleTodo(String id) {
    state = [
      for (final todo in state)
        if (todo.id == id) todo.copyWith(isCompleted: !todo.isCompleted) else todo,
    ];
  }

  // 删除待办事项
  void deleteTodo(String id) {
    state = state.where((todo) => todo.id != id).toList();
  }

  // 清除已完成
  void clearCompleted() {
    state = state.where((todo) => !todo.isCompleted).toList();
  }
}

// 待办事项Provider
final todosProvider = StateNotifierProvider<TodosNotifier, List<TodoItem>>((ref) {
  return TodosNotifier();
});

// 统计Providers
final totalTodosProvider = Provider<int>((ref) {
  final todos = ref.watch(todosProvider);
  return todos.length;
});

final completedTodosProvider = Provider<int>((ref) {
  final todos = ref.watch(todosProvider);
  return todos.where((todo) => todo.isCompleted).length;
});

final activeTodosProvider = Provider<int>((ref) {
  final todos = ref.watch(todosProvider);
  return todos.where((todo) => !todo.isCompleted).length;
});

// 过滤类型Provider
enum TodoFilter { all, active, completed }

final todoFilterProvider = StateProvider<TodoFilter>((ref) => TodoFilter.all);

// 过滤后的待办事项Provider
final filteredTodosProvider = Provider<List<TodoItem>>((ref) {
  final filter = ref.watch(todoFilterProvider);
  final todos = ref.watch(todosProvider);

  switch (filter) {
    case TodoFilter.active:
      return todos.where((todo) => !todo.isCompleted).toList();
    case TodoFilter.completed:
      return todos.where((todo) => todo.isCompleted).toList();
    case TodoFilter.all:
    default:
      return todos;
  }
});
